import { Drawer, Popper, Card } from '@/components';
import { DeleteIcon, HelpIcon } from '@/components/icons';
import { useQuery } from 'react-query';
import { request } from '@/request';
import { useState } from 'react';
import { toRelativeTime, getIcon } from '@/utils';
import { NoticeType } from '@/types';
import { useModal, useGlobalVar } from '@/hooks';

type Notice = {
   _id: string;
   msg: string;
   groupName: string;
   createdAt: string;
   type: NoticeType;
   status: 'read' | 'unread';
};

const TimeBlock = ({ children }) => (
   <div className="text-xs text-right text-gray-500">{children}</div>
);

const Notice = () => {
   const [list, setList] = useState<Array<Notice>>([]);
   const [selectedKeys, setSelectedKeys] = useState([]);
   const { isOpen, openModal, closeModal } = useModal();
   const { isNoticeNew, refetchNoticeStatus } = useGlobalVar();

   const { refetch } = useQuery(
      `notices/${new Date().getTime()}`,
      async () => {
         const res = await request(`/notices`);
         setList(res.list);
      },
      {
         enabled: false,
      }
   );

   const handleOpen = () => {
      refetch();
      openModal();
   };

   const handleReject = (noticeId: string) => {
      request('notices/reject', {
         method: 'POST',
         data: {
            noticeId,
         },
         success: () => {
            refetch();
            refetchNoticeStatus();
         },
         showSuccess: true,
      });
   };

   const handleAccept = (noticeId: string) => {
      request('notices/accept', {
         method: 'POST',
         data: {
            noticeId,
         },
         success: () => {
            refetch();
            refetchNoticeStatus()();
         },
         showSuccess: true,
      });
   };

   const handleDelete = () => {
      request('notices', {
         method: 'DELETE',
         data: {
            ids: selectedKeys,
         },
         success: () => {
            refetch();
            refetchNoticeStatus();
         },
         showSuccess: true,
      });
   };

   const handleSwipeLeft = (item: Notice) => {
      if (item.status === 'read') return;
      request(`notices/read`, {
         method: 'Post',
         data: {
            noticeId: item._id,
         },
         success: () => {
            refetch();
            refetchNoticeStatus();
         },
      });
   };

   const handleSwipeRight = (id: string) => {
      setSelectedKeys((prev) => {
         if (prev.includes(id)) {
            return prev.filter((key) => key !== id);
         }
         return [...new Set([...prev, id])];
      });
   };

   return (
      <>
         <span onClick={handleOpen} className="inline-block relative">
            {getIcon('notice', {
               badge: isNoticeNew,
            })}
         </span>
         <Drawer
            icon="notice"
            title="通知"
            open={isOpen}
            onClose={closeModal}
            moreInfo={
               <div className="space-x-2">
                  {selectedKeys.length !== 0 && (
                     <Popper
                        popperContent={
                           <div className="color-disabled text-xs">
                              确定要删除吗？
                           </div>
                        }
                        showConfirm
                        onConfirm={handleDelete}
                     >
                        <DeleteIcon size={18} type="danger" />
                     </Popper>
                  )}

                  <Popper
                     popperContent={
                        <div className="color-disabled text-xs">
                           <div>左滑卡片可设为已读状态;</div>
                           <div>右滑卡片可选中卡片;</div>
                        </div>
                     }
                  >
                     <HelpIcon size={18} />
                  </Popper>
               </div>
            }
         >
            {list.length === 0
               ? '暂无通知'
               : list.map((item) => {
                    let borderCls = '';
                    const isActive = selectedKeys.includes(item._id);
                    if (isActive) {
                       borderCls = 'border-red-300';
                    }
                    return (
                       <Card
                          key={item._id}
                          onSwipeLeft={handleSwipeLeft.bind(null, item)}
                          onSwipeRight={handleSwipeRight.bind(null, item._id)}
                          isbadge={item.status === 'unread'}
                          isAnimate={true}
                          className={borderCls}
                          deps={[selectedKeys]}
                       >
                          {item.msg}
                          <div className="flex justify-between items-center">
                             <TimeBlock>
                                {toRelativeTime(item.createdAt)}
                             </TimeBlock>
                             <div className="space-x-1 flex">
                                {item.type ===
                                   NoticeType.RECEIVE_INVITATION && (
                                   <>
                                      <button
                                         className="text-xs px-1"
                                         onClick={handleAccept.bind(
                                            null,
                                            item._id
                                         )}
                                      >
                                         同意
                                      </button>
                                      <button
                                         className="text-xs px-1 bg-white border text-red-400"
                                         onClick={handleReject.bind(
                                            null,
                                            item._id
                                         )}
                                      >
                                         拒绝
                                      </button>
                                   </>
                                )}
                             </div>
                          </div>
                       </Card>
                    );
                 })}
         </Drawer>
      </>
   );
};

export default Notice;
